package org.lex.collection.tree.diff;

import java.util.Iterator;

import org.lex.collection.tree.ITreeNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TreeComparator {
	protected Logger log = LoggerFactory.getLogger(TreeComparator.class);
	protected INodeComparator nodeComparator = null;
	protected DiffSet diffSet = new DiffSet();

	public TreeComparator(INodeComparator nodeComparator) {
		this.nodeComparator = nodeComparator;
	}

	public DiffSet compareTree(ITreeNode oldTree, ITreeNode newTree) {
		nodeComparator.compareNodes(this.diffSet, oldTree.getChildren(), newTree.getChildren());
		while (true) {
			Diff<ITreeNode> top = null;
			for (Iterator<Diff<ITreeNode>> iter = diffSet.sameOrUpdate.iterator(); iter.hasNext();) {
				Diff<ITreeNode> p = iter.next();
				if (false == p.visited) {
					top = p;
					break;
				}
			}
			if (null == top) {
				break;
			}
			top.visited = true;
			DiffSet r = this.compareTree(top.oldObject, top.newObject);
			diffSet.added.addAll(r.added);
			diffSet.deleted.addAll(r.deleted);
		}
		return diffSet;
	}

	public ITreeNode buildDiffTree() {
		return new DiffSetUtils().buildDiffTree(diffSet, nodeComparator);
	}
}
